package com.roc.web.action.windcontroll;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.BlackListBean;
import com.roc.bean.WhiteListBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.ServiceException;
import com.roc.service.white.IWhiteService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.OperatorQueryAction;
@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/whitelist")
public class WhiteListAction extends PaginationBaseAction {
	private Logger logger=LogManager.getLogger(WhiteListAction.class);
	private WhiteListSearchCondition searchCondition;
	private WhiteListBean white;
	private String mchtId;
	private File file;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IWhiteService whiteService;
	/**
	 * 初始化白名单页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/windControllSta/whitelist.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	   
    }
	
	/**
	 * 白名单列表页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "whitelistview", results = { @Result(name = "success", location = "/pages/windControllSta/whitelist.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String blackView() throws Exception{
		try {			
			if(searchCondition==null){
				searchCondition=(WhiteListSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new WhiteListSearchCondition();
				}
			}		

			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);				
				List<WhiteListBean> lists=new ArrayList<WhiteListBean>();
				String remark=null;
				String[] str=null;
				if(searchRsList!=null&&searchRsList.size()>0)
				{
					Iterator<?> iterator=searchRsList.iterator();
					while(iterator.hasNext())
					{
						Object[] obj=(Object[]) iterator.next();
						WhiteListBean bean=new WhiteListBean();
						bean.setMchtId(Constance.Null2EmptyTrim(obj[0]));
						bean.setMchtName(Constance.Null2EmptyTrim(obj[1]));
						bean.setStatus(Constance.Null2EmptyTrim(obj[2]));
						remark=Constance.Null2EmptyTrim(obj[3]);
						if(remark.equals("") || !remark.contains(",") || remark.split(",").length<3){
							bean.setOpr("-");
							bean.setDate("-");
							bean.setTime("-");
						}
						else{
							str=remark.split(",");
							bean.setOpr(str[0]);
							bean.setDate(str[1]);
							bean.setTime(str[2]);
						}
						lists.add(bean);
					}
					searchRsList.clear();
					searchRsList.addAll(lists);
				}
			}
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
	   return SUCCESS;
    }
	/**
	 * 初始化添加白名单
	 * @return
	 */
	@Action(value = "addwhitejsp", results = { @Result(name = "success", location = "/pages/windControllSta/addWhite.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addWhiteview()throws Exception
	{
		Operators opr=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		white=new WhiteListBean();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String date=sdf.format(new Date());
		white.setDate(date.substring(0, 8));
		white.setTime(date.substring(8));
		white.setOpr(opr.getAccountNo());
		return SUCCESS;		
	}
	/**
	 * 添加白名单
	 * @return
	 */
	@Action(value = "addWhite", results = { @Result(name = "success", location = "/pages/windControllSta/whitelist.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addWhiteList()
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			whiteService.addWhiteList(white, op);
			addActionMessage("添加成功!");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("添加白名单失败~");
		}
		return SUCCESS;		
	}
	/**
	 * 修改页面初始化
	 * @return
	 */
	@Action(value = "updateWhitelistInit", results = { @Result(name = "success", location="/pages/windControllSta/addWhite.jsp")})
	public String updateInit()
	{
		try {
			white=whiteService.findByWhiteNum(white.getMchtId());
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
			String date=sdf.format(new Date());
			white.setDate(date.substring(0, 8));
			white.setTime(date.substring(8));
			getRequest().setAttribute("flag", "update");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("修改页面初始化失败~");
		}
		return SUCCESS;
	}
	/**
	 * 更改白名单
	 * @return
	 */
	@Action(value = "updateWhitelist", results = { @Result(name = "success", location="/pages/windControllSta/whitelist.jsp")})
	public String updateStatus()
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			white.setMchtId(mchtId);
			whiteService.updateWhiteList(white, op);
			addActionMessage("修改成功!");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("更改白名单失败~");
		}
		return SUCCESS;
	}
	/**
	 * 批量导入初始化页面
	 * @return
	 */
	@Action(value = "startExportJsp", results = { @Result(name = "success", location = "/pages/windControllSta/exportWhite.jsp")
    })	
	public String moreBlackList()throws Exception
	{
		return SUCCESS;
	}
	/**
	 * 批量导入白名单
	 * @return
	 */
	@Action(value = "addwhitelist", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(name = "success",location = "/pages/windControllSta/exportWhite.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")})
	public String addBlackLists()
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap=whiteService.insertExportData(file, op);
			if(resultMap.containsKey("result"))
			{	
				Object objMsg=resultMap.get("result");
				addActionMessage(String.valueOf(objMsg));
			}		
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("批量导入白名单失败~");
		}
		return SUCCESS;		
	}
	/**
	  * 验证商户号是否已存在数据库中
	  */
	@Action(value="validateMchtId")
	public void validateMchtId()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		boolean value=true;
		try {
			white=whiteService.findByWhiteNum(white.getMchtId());
			if(white!=null)
			{
				value=false;
			}
			response.getWriter().print(value);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("验证商户号错误!!!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_WHITE_LIST_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_WHITE_LIST_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return null;
	}
	public WhiteListSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(WhiteListSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public WhiteListBean getWhite() {
		return white;
	}
	public void setWhite(WhiteListBean white) {
		this.white = white;
	}

	public String getMchtId() {
		return mchtId;
	}

	public void setMchtId(String mchtId) {
		this.mchtId = mchtId;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	
}
